import { injectable } from '@/services/service'

@injectable
/** 画设备服务 */
export default class DataService {
  private datas_ = [] as number[][]
  get datas () {
    return this.datas_
  }

  private artboard_ = {
    minX: 0,
    maxX: 0,
    minY: 0,
    maxY: 0
  }

  get artboatd () {
    return this.artboard_
  }

  setDatas (datas: number[][]) {
    this.datas_ = datas
    this.artboard_.minX = Math.min(...datas.map(v => v[0]).flat())
    this.artboard_.maxX = Math.max(...datas.map(v => v[0]).flat())
    this.artboard_.minY = Math.min(...datas.map(v => v[1]).flat())
    this.artboard_.maxY = Math.max(...datas.map(v => v[1]).flat())
  }

  draw (base: Snap.Paper, type = 0) {
    for (const data of this.datas) {
      if (type === 0) {
        const len = Math.max(0.0, Math.min(1.0, Math.sqrt(data[2] ** 2 + data[3] ** 2)))
        const color = `rgb(${Math.floor(255 * len)}, ${Math.floor(255 * (1 - len))}, ${Math.floor(255 * (1 - len))})`
        base.circle(data[0], data[1], 0.5).attr({
          stroke: color,
          fill: color
        })
        let angle = Math.atan2(data[3], data[2])
        base.line(data[0], data[1], data[0] + 12 * Math.cos(angle), data[1] + 12 * Math.sin(angle))
          .attr({
            stroke: color
          })
        base.polygon([
          data[0] + 12 * Math.cos(angle), data[1] + 12 * Math.sin(angle),
          data[0] + 8 * Math.cos(angle + Math.PI / 15), data[1] + 8 * Math.sin(angle + Math.PI / 15),
          data[0] + 8 * Math.cos(angle - Math.PI / 15), data[1] + 8 * Math.sin(angle - Math.PI / 15)
        ]).attr({
          fill: color
        })
      } else {
        let color = `rgb(${Math.floor(255 * Math.abs(data[4]))}, ${Math.floor(255 * (1 - Math.abs(data[4])))}, ${Math.floor(255 * (1 - Math.abs(data[4])))})`
        base.line(data[0], data[1], data[0] + 5 * this.signal(data[4]), data[1])
          .attr({
            stroke: color,
            'stroke-width': 0.5
          })
        base.polygon([
          data[0] + 5 * this.signal(data[4]), data[1],
          data[0] + 5 * this.signal(data[4]) - 2.5 * this.signal(data[4]), data[1] - 1.2,
          data[0] + 5 * this.signal(data[4]) - 2.5 * this.signal(data[4]), data[1] + 1.2
        ]).attr({
          fill: color
        })
        color = `rgb(${Math.floor(255 * Math.abs(data[5]))}, ${Math.floor(255 * (1 - Math.abs(data[5])))}, ${Math.floor(255 * (1 - Math.abs(data[5])))})`
        base.line(data[0], data[1], data[0], data[1] + 5 * this.signal(data[5]))
          .attr({
            stroke: color,
            'stroke-width': 0.5
          })
        base.polygon([
          data[0], data[1] + 5 * this.signal(data[5]),
          data[0] - 1.2, data[1] + 5 * this.signal(data[5]) - 2.5 * this.signal(data[5]),
          data[0] + 1.2, data[1] + 5 * this.signal(data[5]) - 2.5 * this.signal(data[5])
        ]).attr({
          fill: color
        })
      }
    }
  }

  private signal (x: number) {
    return x > 0 ? 1 : -1
  }
}
